/*
 * 机构
 */
package com.juzhencms.apps.busi.service;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.support.hsf.HSFJSONUtils;
import com.juzhencms.apps.base.common.config.Config;
import com.juzhencms.apps.base.common.database.DBTable;
import com.juzhencms.apps.base.common.util.StringUtil;
import com.juzhencms.apps.base.common.util.WebUtil;

@Service
public class OrganizationService extends CommonService {
	
	@Autowired
	private DictionaryService dictionaryService;

	@Autowired
	private UserService userService;
	
	/*
	 * getLists：获取(受机构限制)机构列表
	 * @param fields 查询字段默认
	 * @param where String 条件，比如：name like ?
	 * @param whereParamList list 条件参数，如：List whereParamList=new ArrayList();whereParamList.add("%机构%");
	 * @param orderBy 排序 默认 order by position asc,id asc
	 * @param pageIndex 页码
	 * @param pageSize 每页页数 使用时需与pageIndex都设置 
	 * @param is_not_limit_org 不设置机构限制 默认0设置 1不设置
	 * @return list
	 * 应用：OrganizationService.getAllSite(null, null, null, null, 0, 0,0);
	 */
	public List getLists(String fields, String where, List whereParamList, String orderBy, int pageIndex,
			int pageSize,int is_not_limit_org) {

		// 查询字段
		if (fields == null || fields.equals("")) {
			fields = " * ";
		}

		// 查询条件
		String setWhere = "  where  1=1  ";
		if (where != null && !where.equals("")) {
			setWhere += " and "+where;
		}
		
		//机构限制：系统管理员、超级管理员以外的管理员用户都需要加机构限制
		if(is_not_limit_org == 0) {
			String getLoginUserOrgIds = userService.getLoginUser().getSubOrgIds();
			/*if( userService.getLoginUserPermissions().get("root")==null && !getLoginUserOrgIds.equals("")) {
				setWhere += " and id in ("+getLoginUserOrgIds+") ";
			}*/
			setWhere += " and id in ("+getLoginUserOrgIds+") ";
		}
		

		// 排序：默认ID倒序
		if (orderBy == null || orderBy.equals("")) {
			orderBy = " order by position asc,id asc";
		}


		// 页码，0代表全显示
		String setLimit = "";
		if (pageIndex > 0 && pageSize > 0) {
			setLimit = " limit ?,? ";
			//
			int start=0;
			if(pageIndex>1){
				start=(pageIndex-1)*pageSize;
			}
			whereParamList.add(start);
			whereParamList.add(pageSize);
		}

		// 语句
		String sql = "select " + fields + " from " + DBTable.organization + setWhere + orderBy + setLimit;

		// 参数条件
		List dataList = null;
		if (whereParamList != null && whereParamList.size() > 0) {
			dataList = this.getJdbcDao().querySql(sql, whereParamList.toArray());
		} else {
			dataList = this.getJdbcDao().querySql(sql);
		}
		return dataList;

	}
	
	/*
	 * 获取(受机构限制)站点列表
	 */
	public List getLists(String fields) {
		// 查询字段
		if (fields == null || fields.equals("")) {
			fields = " * ";
		}
		return this.getLists(fields, null, null, null, 0, 0,0);
	}
	
	/*
	 * getDetail：获取（机构限制）指定机构信息
	 * @param fields 查询字段默认
	 * @param where String 条件，比如：name like ?
	 * @param whereParamList list 条件参数，如：List whereParamList=new ArrayList();whereParamList.add("%机构%");
	 * @param orderBy String 排序
	 * @param is_not_limit_org 不设置机构限制 默认0设置 1不设置
	 * @return Map
	 */
	public Map getDetail(String fields, String where, List whereParamList,String orderBy,int is_not_limit_org ) {
		
		// 查询字段
		if (fields == null || fields.equals("")) {
			fields = " * ";
		}

		// 查询条件
		String setWhere = "  where  1=1  ";
		if (where != null && !where.equals("")) {
			setWhere += " and "+where;
		}
		
		// 排序：默认ID倒序
		if (orderBy == null) {
			orderBy = " order by position asc,id asc";
		}

		// 仅查询一条
		String setLimit = " limit 1 ";
		
		// 语句
		String sql = "select " + fields + " from " + DBTable.organization + setWhere + orderBy + setLimit;

		// 参数条件
		Map data = new HashMap();
		if (whereParamList != null && whereParamList.size() > 0) {
			data =  this.getJdbcDao().queryRow(sql,whereParamList.toArray());	
		} else {
			data =  this.getJdbcDao().queryRow(sql);	
		}
		return data;
	}
	
	/*
	 * getDetail：获取（机构限制）指定机构信息
	 */
	public Map getDetail(int id,String fields) {
		if(id<=0) {
			return null;
		}
		String where = " id =  "+id;
		return this.getDetail(fields, where,null,null,0);
	}
	
	
	//获取机构分类树（扁平数据）,应用场景：机构功能模块外表单外组件使用
	public List getOrgTree(int parent_id) {
		List orgList = this.getJdbcDao().querySql("select id,name,parent_id from " + DBTable.organization
				+ " where del_flag=0 and id=? order by position asc,id desc", new Object[] {parent_id});
		if(orgList!=null && orgList.size()>0) {
			
			Map parentNode=(Map)orgList.get(0);
			parentNode.put("open", true);
			
			//查询所有父级id，用以减少下级的查询次数
			List parentList=this.getJdbcDao().querySql("select distinct parent_id from " + DBTable.organization+ " where del_flag=0 ");
			Map parentsIdMap=new HashMap();
			if(parentList!=null) {
				for(int i=0;i<parentList.size();i++) {
					Map row=(Map)parentList.get(i);
					parentsIdMap.put(row.get("parent_id").toString(), 1);
				}
			}
			
			List subList=getSubOrgTree(parent_id,parentsIdMap);
			if(subList!=null && subList.size()>0) {
				orgList.addAll(subList);
			}			
			return orgList;
		}else {
			return null;
		}
	}
	
	private List getSubOrgTree(int parent_id,Map parentsIdMap) {
		// TODO Auto-generated method stub
		List orgList = this.getJdbcDao().querySql("select id,name,parent_id from " + DBTable.organization
				+ " where del_flag=0 and parent_id=? order by position asc,id desc", new Object[] {parent_id});
		List subList=new ArrayList();
		if (orgList != null && orgList.size() > 0) {
			for (int i = 0; i < orgList.size(); i++) {
				Map row = (Map) orgList.get(i);
				row.put("pId", row.get("parent_id"));
				/*//如果是根节点或当前用户所在机构，展开下级节点
				if(row.get("parent_id").toString().equals("0") || row.get("id").toString().equals(""+userService.getLoginUser().getOrgId())) {
					row.put("open",true);
				}*/
				
				if(parentsIdMap.get(row.get("id").toString())!=null) {
					List childrenData = this.getSubOrgTree(new Integer(row.get("id").toString()),parentsIdMap);
					if (childrenData != null && childrenData.size()>0)
						subList.addAll(childrenData);
				}	
			}
			orgList.addAll(subList);
			return orgList;
		} else {
			return null;
		}
	}
	
	//获取本机构以及子机构ID集
	public String getOrgIds(int parent_id) {
		
//		if(parent_id <=0) {
//			return "";
//		}
		
		//该机构信息不存在则返回空字符串
		if(parent_id > 0 ) {
			Map getThisTmp = this.getJdbcDao().queryRow("select id from "+DBTable.organization+" where id=? and del_flag = 0 ",new Object[]{parent_id});	
			if(getThisTmp == null) {
				return "";
			}
		}

		List whereParamList=new ArrayList();
		String where=" where del_flag=0 and  parent_id=?  " ;
		whereParamList.add(parent_id);
		where+=" order by position asc,id desc";

		List OrgList = this.getJdbcDao().querySql("select id,parent_id from " + DBTable.organization
				+ where, whereParamList.toArray());
		StringBuffer ids = new StringBuffer();
		if(parent_id > 0) {
			ids.append(parent_id+"".toString()).append(",");
		}
		if (OrgList != null && OrgList.size() > 0) {
			for (int i = 0; i < OrgList.size(); i++) {
				Map row = (Map) OrgList.get(i);
				//拼接
				int sonId = new Integer(row.get("id").toString());
				Map doubleSon = this.getJdbcDao().queryRow("select id from "+DBTable.organization+" where parent_id=?  limit 1",new Object[]{sonId});
				if(doubleSon!=null && doubleSon.size() > 0) {
					String childOrg = this.getOrgIds(sonId);
					ids.append(childOrg).append(",");
				} else {
					ids.append(row.get("id").toString()).append(",");
				}
			}
		}
		String returnIds = (ids!=null && ids.length()>0)?ids.deleteCharAt(ids.length() - 1).toString():"";
		return returnIds;
	}
	
	//获取本机构的上级机构ID集
	public String getParentOrgIds(int id) {
				
		List whereParamList=new ArrayList();
		String where=" where del_flag=0 and  id=?  " ;
		whereParamList.add(id);
		Map getParentOrg = this.getJdbcDao().queryRow("select  id,parent_id from "+DBTable.organization+where,whereParamList.toArray());
		StringBuffer ids = new StringBuffer();
		if(getParentOrg != null  ) {
			if(!getParentOrg.get("parent_id").toString().equals("0")) {
				//拼接
				int parent_id = new Integer(getParentOrg.get("parent_id").toString());
				ids.append(parent_id+"").append(","); 
				String parentOrg = this.getParentOrgIds(parent_id);
				if(!parentOrg.equals("")) {
					ids.append(parentOrg).append(","); 
				}
			} 
		} else {
			return ""; 
		}
		String returnIds = "";
		if(ids!=null && ids.length()>0){
			returnIds = ids.deleteCharAt(ids.length() - 1).toString();
		}
		return returnIds;
	}
	
	
	//判断机构有没有权限
	public boolean isAuth(int id) {

		boolean result = true;
		//机构限制
		String getLoginUserOrgIds = userService.getLoginUser().getSubOrgIds();
		if(!getLoginUserOrgIds.equals("")) {
			String[] splitValues = getLoginUserOrgIds.split(",");
		    List<String> orgList = Arrays.asList(splitValues);
		    if(!orgList.contains(id+"")){
		    	result = false;
		    }
		}
		return result;
	}
	

}
